package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.sl.au.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.sl.au.entity.*;

/*
 * 售后计划
 */

@RestController
@RequestMapping(value = "/ui/afterSalePlan")
public class AfterSalePlanController extends BaseController {

	@Autowired
	CustomerService customerService;
	
	@Autowired
	SaleAreaService saleAreaService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	ContractService contractService;
	
	@Autowired
	AfterSaleMaintainService afterSaleMaintainService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("afterSalePlan/planindex");
		return modelAndView;
	}
	
	@RequestMapping(value="getpage",method = RequestMethod.GET)
	public Map<String, Object> getpage(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		long count = 0;
		if (key != null) {
			List<Contract> contracts=contractService.getAfterSaleContracts(start, length, key, null, null);
			count = contractService.getRepository().getAfterSaleContractsCount2(key);
			map.put("data", contracts);
		} else {
			List<Contract> contracts=contractService.getAfterSalePage(start, length, key, null, null);
			count = contractService.getRepository().getAfterSaleContractsCount1();
			map.put("data", contracts);
		}
		
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 获取合同弹窗
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getContract",method = RequestMethod.GET)
	public Map<String, Object> getContract(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String auditState="通过";
		long count = 0;
		if (key != null) {
			List<Contract> contracts=afterSaleMaintainService.getAfterSaleContracts(start, length, key, null, null);
			count = afterSaleMaintainService.getRepository1().getAfterSaleContractsCount2(key,auditState);
			map.put("data", contracts);
		} else {
			List<Contract> contracts=afterSaleMaintainService.getAfterSalePage(start, length, key, null, null);
			count = afterSaleMaintainService.getRepository1().getAfterSaleContractsCount1(auditState);
			map.put("data", contracts);
		}

		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 编辑合同维护计划
	 * @return
	 */
	@RequestMapping(value="/editPlan/{id}",method = RequestMethod.GET)
	public ModelAndView editPlan(@PathVariable String id, HttpServletRequest request) {
		ModelAndView mv = this.createLayoutView("afterSalePlan/planEdit");
		Contract contract = contractService.getRepository().findOne(id);

		mv.addObject("contract", contract);
		mv.addObject("memo", contract.getMemo());
		return mv;
	}
	
	/**
	 * 项目合同细目泵数据显示
	 * @return
	 */
	@RequestMapping(value = "getDevice", method = RequestMethod.GET)
	public Map<String, Object> getDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String contractId=request.getParameter("contractID");
		if (contractId==null){
			contractId="";
		}
		List<DeviceDetail> devices = afterSaleMaintainService.getAllPlanDetails(start, length, contractId, null, null);
		Long count = (long) afterSaleMaintainService.getAllPlanDetailsCount(contractId);
		map.put("data", devices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 保存设备绑定选择的方案
	 * @return
	 */
	@RequestMapping(value = "/selectScheme/{deviceID}/{schemeID}/{contractID}", method = RequestMethod.GET)
	public Map<String, Object> selectScheme(@PathVariable String deviceID, 
											@PathVariable String schemeID,
											@PathVariable String contractID) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<MaintainItem> items = new ArrayList<MaintainItem>();
		int count = 0;
		if (StringUtils.hasText(schemeID)) {
			items = afterSaleMaintainService.getRepository().getAllMaintainItemBySchemeID(schemeID);
			count = items.size();
		}
		if (count>0){
			DeviceDetail deviceDetail = afterSaleMaintainService.getDeviceDetailRepository().findOne(deviceID);
			afterSaleMaintainService.getRepository().deleteItemByDeviceId(deviceID);
			deviceDetail.setMaintainSchemeID(schemeID);
			for (MaintainItem item : items){
				MaintainItemDevice mid = new MaintainItemDevice();
				mid.setContractID(contractID);
				mid.setDeviceID(deviceID);
				mid.setStartDate(deviceDetail.getLeaveFactoryDate());//每个维护计划的开始时间都为出厂时间
				mid.setLeaveFactoryCode(deviceDetail.getLeaveFactoryCode());
				mid.setMaintainPeriod(item.getMaintainPeriod());
				mid.setMaintainProject(item.getMaintainProject());
				mid.setAnnouncement(item.getAnnouncement());
				mid.setMemo(item.getMemo());
				//每新增一条保存一条，确保顺序不乱
				afterSaleMaintainService.getRepository2().save(mid);
			}
			afterSaleMaintainService.getDeviceDetailRepository().save(deviceDetail);
			/*long time = startDate.getTime(); // 得到出厂日期的毫秒数
			int day = 0;
			for (MaintainItem item : items){
				long dayTime = 24*60*60*1000; // 一天的时间转换成毫秒数
				time+=day*dayTime; // 相加得到新的毫秒数
				startDate = new Date(time); // 将毫秒数转换成日期
				day = item.getMaintainPeriod();//得到当前项目周期天数
				MaintainItemDevice mid = new MaintainItemDevice();
				mid.setContractID(contractID);
				mid.setDeviceID(deviceID);
				mid.setStartDate(startDate);
				mid.setLeaveFactoryCode(deviceDetail.getLeaveFactoryCode());
				mid.setMaintainPeriod(item.getMaintainPeriod());
				mid.setMaintainProject(item.getMaintainProject());
				mid.setAnnouncement(item.getAnnouncement());
				mid.setMemo(item.getMemo());
				//每新增一条保存一条，确保顺序不乱
				afterSaleMaintainService.getRepository2().save(mid);
			}*/
		}
		map.put("code", "0");
		return map;
	}
	
	/**
	 * 保存当前设备维护计划
	 * @return
	 */
	@RequestMapping(value = "/savePlan", method = RequestMethod.POST)
	public Map<String, Object> savePlan(@RequestBody MaintainItemDevice maintainItemDevice, 
			  							   HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		long count = 1;
		if (maintainItemDevice!=null&&maintainItemDevice.getId()!=null){
			MaintainItemDevice mdOld = afterSaleMaintainService.getRepository2().findOne(maintainItemDevice.getId());
			if (mdOld!=null){
				maintainItemDevice.setCreateTime(mdOld.getCreateTime());
				maintainItemDevice.setStartDate(mdOld.getStartDate());
			}else if (maintainItemDevice.getDeviceID()!=null && !maintainItemDevice.getDeviceID().equals("")){
				DeviceDetail dd = afterSaleMaintainService.getDeviceDetailRepository()
								.findOne(maintainItemDevice.getDeviceID());
				Date startDate = new Date();
				if (dd.getLeaveFactoryDate()!=null){
					startDate = dd.getLeaveFactoryDate();
				}
				maintainItemDevice.setStartDate(startDate);
				count = afterSaleMaintainService.getRepository()
								.getDeviceItemCount(maintainItemDevice.getDeviceID());
				if (count == 0){
					dd.setMaintainSchemeID("1");
					afterSaleMaintainService.getDeviceDetailRepository().save(dd);
				}
			}
			afterSaleMaintainService.getRepository2().save(maintainItemDevice);
			/*//新增
			if (maintainItemDevice.getId()==null || maintainItemDevice.getId().equals("")){
					List<MaintainItemDevice> maintainItemDevices = afterSaleMaintainService.getRepository()
													.getMaintainItemDevice(maintainItemDevice.getDeviceID());
					Date startDate = null;
					int day = 0;
					if (maintainItemDevices.size()>0){
						MaintainItemDevice md = maintainItemDevices.get(maintainItemDevices.size()-1);
						startDate = md.getStartDate();
						day = md.getMaintainPeriod();
						long time = startDate.getTime(); // 得到出厂日期的毫秒数
						long dayTime = 24*60*60*1000; // 一天的时间转换成毫秒数
						time+=day*dayTime; // 相加得到新的毫秒数
						startDate = new Date(time); // 将毫秒数转换成日期
					}else{
						DeviceDetail dd = afterSaleMaintainService.getDeviceDetailRepository()
													.findOne(maintainItemDevice.getDeviceID());
						startDate = dd.getLeaveFactoryDate();
					}
			}else{//编辑
				List<MaintainItemDevice> maintainItemDevices = afterSaleMaintainService.getRepository()
						.getMaintainItemDeviceByStartDate(maintainItemDevice.getDeviceID(), maintainItemDevice.getStartDate());
				Date startDate = maintainItemDevice.getStartDate();
				int day = maintainItemDevice.getMaintainPeriod();
				long time = startDate.getTime(); // 得到开始时间的毫秒数
				for (MaintainItemDevice mid : maintainItemDevices){
					long dayTime = 24*60*60*1000; // 一天的时间转换成毫秒数
					time+=day*dayTime; // 相加得到新的毫秒数
					startDate = new Date(time); // 将毫秒数转换成日期
					day = mid.getMaintainPeriod();//得到当前项目周期天数
					mid.setStartDate(startDate);
				}
				afterSaleMaintainService.getRepository2().save(maintainItemDevices);
			}*/
		}
		map.put("count", count);
		return map;
	}
	
	/**
	 * 获得当前设备的维护项目
	 * @return
	 */
	@RequestMapping(value="/getDeviceItem",method = RequestMethod.GET)
	public Map<String, Object> getItem(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String deviceID=request.getParameter("deviceID");
		String key = null;
		Long count = (long) 0;
		if (StringUtils.hasText(deviceID)){
			key = deviceID;
			count = afterSaleMaintainService.getRepository().getDeviceItemCount(deviceID);
		}
		List<MaintainItemDevice> maintainItemDevices = afterSaleMaintainService.getMaintainItemDevice(start, length, key, null, null);
		map.put("data", maintainItemDevices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 获得当前合同的维护项目
	 * @return
	 */
	@RequestMapping(value="/getPlans",method = RequestMethod.GET)
	public Map<String, Object> getPlans(HttpServletRequest request){
		Map<String, Object> map=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String contractID=request.getParameter("contractID");
		String key = null;
		Long count = (long) 0;
		if (StringUtils.hasText(contractID)){
			key = contractID;
			count = afterSaleMaintainService.getRepository().getPlansCount(contractID);
		}
		List<MaintainItemDevice> maintainPlans = afterSaleMaintainService.getMaintainPlans(start, length, key, null, null);
		map.put("data", maintainPlans);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * /删除维护项目
	 */
	@RequestMapping(value = "/delItem", method = RequestMethod.GET)
	public Map<String, Object> delItem(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		String deviceID = null;
		int count = 1;
		if (id.length>0){
			MaintainItemDevice maintainItemDevice = afterSaleMaintainService.getRepository2().findOne(id[0]);
			if (maintainItemDevice!=null){
				deviceID = maintainItemDevice.getDeviceID();
			}
		}
		List<MaintainItemDevice> items = new ArrayList<>();
		for (int i = 0; i < id.length; i++) {
			String itemId = id[i];
			MaintainItemDevice item = new MaintainItemDevice();
			item.setId(itemId);
			items.add(item);
		}
		afterSaleMaintainService.getRepository2().deleteInBatch(items);
		if (deviceID!=null){
			List<MaintainItemDevice> mids = afterSaleMaintainService.getRepository().getMaintainItemDevice(deviceID);
			count = mids.size();
			DeviceDetail deviceDetail = afterSaleMaintainService.getDeviceDetailRepository().findOne(deviceID);
			if (count==0){
				deviceDetail.setMaintainSchemeID(null);
				afterSaleMaintainService.getDeviceDetailRepository().save(deviceDetail);
			}
			/*else{
				Date startDate = deviceDetail.getLeaveFactoryDate();
				int day = 0;
				long time = startDate.getTime(); // 得到开始时间的毫秒数
				for (int i = 0; i < count; i++) {
					long dayTime = 24 * 60 * 60 * 1000; // 一天的时间转换成毫秒数
					time += day * dayTime; // 相加得到新的毫秒数
					startDate = new Date(time); // 将毫秒数转换成日期
					day = mids.get(i).getMaintainPeriod();// 得到当前项目周期天数
					mids.get(i).setStartDate(startDate);
				}
				afterSaleMaintainService.getRepository2().save(mids);
			}*/
		}
		map.put("code", 0);
		map.put("count", count);
		return map;
	}
}
